package com.longteng.lesson2.util;

import com.longteng.lesson2.task.Task2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Component
public class TaskUtil {

    @Autowired
    ThreadPoolTaskScheduler taskScheduler;

    @Bean
    public ThreadPoolTaskScheduler init(){
        return new ThreadPoolTaskScheduler();
    }
    private static Map<String,ScheduledFuture<?>> scheduledFutureMap=new HashMap<>();

    public void addTask(String cron,Task2 task2){
        //时间表达式的初始化，构造方法的参数就是时间的表达式
        Trigger trigger =new CronTrigger(cron);
        ScheduledFuture<?>  scheduledFuture =taskScheduler.schedule(task2,trigger);
        scheduledFutureMap.put(task2.getId(),scheduledFuture);
    }
    //假设说我们有多个任务怎么办？
    public void cancel(String flag){
        ScheduledFuture<?> scheduledFuture =scheduledFutureMap.get(flag);
        scheduledFuture.cancel(true);
    }

    public void modify(String cron,Task2 task2){
        this.cancel(task2.getId());
        this.addTask(cron,task2);
    }



}
